//
// Copyright (c) 2011 Health Market Science, Inc.
//
package com.kmstech.greeting.dao;

import java.lang.reflect.ParameterizedType;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import com.kmstech.greeting.entities.Identify;

public class GenericDaoImpl<T extends Identify> implements GenericDao<T> {
  @PersistenceContext
  protected EntityManager _em;

  @Override
  public void create(Identify entity) {
    _em.persist(entity);
  }

  @Override
  public void update(Identify entity) {
    _em.merge(entity);
  }

  @Override
  public void remove(Identify entity) {
    _em.refresh(entity);
    _em.remove(entity);
  }

  @Override
  public T findById(int id) {
    return _em.find(getEntityClass(), id);
  }

  @SuppressWarnings("unchecked")
  @Override
  public List<T> findAll() {
    Query query = _em.createQuery("from " + getEntityClass().getName());
    return query.getResultList();
  }

  @SuppressWarnings("unchecked")
  protected Class<T> getEntityClass() {
    ParameterizedType ptype = (ParameterizedType) getClass()
        .getGenericSuperclass();

    return (Class<T>) ptype.getActualTypeArguments()[0];

  }
}
